<template>
  <el-dialog title="上传" :width="800" v-model="visible" @close="closeHandler" :destroy-on-close="true">
    <el-card class="el-card-custom" shadow="never" size="small" tabindex="0" @paste.stop="handlePaste">
      <span class="tip-upload">*点击后，粘贴上传</span>
      <el-space class="flx-end">
        <el-button type="primary" @click="onUpload">
          <template #default>上传文件</template>
        </el-button>
      </el-space>
      <div class="mt20">
        <!--        -->
        <el-upload
          v-model:file-list="fileList"
          :class="{ isNone: limitNumber == 1 && state.dataSource.length }"
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          @change="selectFile"
          :limit="limitNumber"
          :multiple="multiple"
          :on-exceed="handleExceed"
          :accept="accept"
        >
          <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-list">
          <div class="list-item" v-for="item in state.dataSource" :key="item.uid" :title="item.name">
            <div class="list-left">
              <div class="mb5 title">{{ item.name }}</div>
              <div class="item-content">
                <el-space>
                  <div>
                    大小: <span style="color: blue">{{ item.unitSize }}</span>
                  </div>
                  <!-- <div>
                    md5:
                    <span style="color: red">
                      <template v-if="item.md5Progress">
                        {{ `${item.md5Progress}%` }}
                      </template>
                      <template v-else>{{ item.md5 }}</template>
                    </span>
                  </div> -->
                </el-space>
                <el-progress class="mt5" v-if="item.progress" :percentage="item.progress" />
              </div>
            </div>
            <el-tag :color="tagMap[item.status].color">
              <span class="write">{{ tagMap[item.status].text }}</span>
            </el-tag>
            <div class="delete" @click="deleteFile(item)">
              <el-icon><Close /></el-icon>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </el-dialog>
</template>

<script setup lang="ts">
import axios from "axios";
import pLimit from "p-limit";
import { CHUNK_SIZE } from "@/constants";
import { ElMessage } from "element-plus";
import { reactive, ref } from "vue";
// import createChunkFileAndMd5 from '../util/createChunkFileAndMd5'
import { convertFileSizeUnit, checkVideoFormat, generateUUID } from "@/utils";
import { checkFileByMd5, initMultPartFile, mergeFileByMd5, deleteFileApi } from "@/api/modules/upload";
import { HttpCodeUploadEnum } from "@/enums/httpEnum";
import type { UploadFileInfoType } from "@/api/interface/index";
import { useUserStore } from "@/stores/modules/user";
import cutFile from "./core/cutFile";
import { MerkleTree } from "./core/MerkleTree";

const emits = defineEmits(["success", "close", "change"]);
let clipboardDataList = ref<any>([]);
const userStore = useUserStore();
// const pathPrefix = "/";
// interface UploadFileProps {
//   prefixData: string;
//   limitNumber: number;
//   multiple: boolean;
//   accept: string;
// }
let n = 0; // 记录数量
const limit = pLimit(3);
const props = defineProps({
  accept: {
    type: String,
    default: "image/jpeg,image/png,image/gif"
  },
  limitNumber: {
    type: Number,
    default: 1
  },
  multiple: {
    type: Boolean,
    default: false
  },
  prefixData: {
    type: String,
    default: ""
  }
});
const visible = defineModel("visible", {
  type: Boolean,
  default: false
});
const fileList = defineModel("file", {
  type: Array,
  default: () => []
});
/** 分片上传时的 file 和上传地址 url */
type ChunkFileUrlType = {
  url: string;
  file: Blob;
};
/** 表格数据类型 */
type FileTableDataType = {
  uid: string;
  name: string;
  size: number;
  unitSize: string;
  md5: string;
  md5Progress: number;
  progress: number;
  file: File;
  chunkCount: number;
  /** 当前文件分片集合 */
  chunkFileList: Blob[];
  /** 已上传的文件大小总和（计算进度条） */
  uploadedSize: number;
  /** 计算MD5中（加载中） | 等待上传 | 上传中  | 上传成功 | 上传失败 */
  status: "preparation" | "preupload" | "uploading" | "success" | "error";
};

//  文件上传过程中的多种状态
const tagMap = {
  preparation: { color: "gold", text: "MD5计算中" },
  preupload: { color: "purple", text: "等待上传" },
  uploading: { color: "blue", text: "上传中" },
  success: { color: "green", text: "上传成功" },
  error: { color: "red", text: "上传失败" }
};
const closeHandler = () => {
  visible.value = false;
  n = 0;
};

const state = reactive<{ dataSource: FileTableDataType[] }>({
  dataSource: []
});
// 删除
const deleteFile = async (item: FileTableDataType) => {
  const i = state.dataSource.findIndex(itm => itm.uid == item.uid);
  state.dataSource.splice(i, 1);
  const j = fileList.value.findIndex(itm => itm.md5 == item.md5);
  const data: any = fileList.value.splice(j, 1);
  if (data && data[0].path) {
    await deleteFileApi({ path: data[0].path });
  }
  emits("close", item);
};
// 选择文件并计算 md5
const selectFile = async (fileItem: any) => {
  const file: any = fileItem.raw;
  if (!file) return;
  try {
    await checkVideoFormat(fileItem);
  } catch (error) {
    ElMessage.error("视频文件编码格式不支持，请使用H264编码格式");
    fileList.value = fileList.value.filter(item => item.md5);
    return;
  }
  const chunkCount = Math.ceil((file.size ?? 0) / CHUNK_SIZE);
  // 展示给 table的数据，部分参数用于初始化
  const dataItem: FileTableDataType = {
    uid: fileItem.uid,
    name: file.name,
    size: file.size ?? 0,
    unitSize: convertFileSizeUnit(file.size),
    md5: "",
    md5Progress: 0,
    progress: 0,
    chunkCount,
    file: file,
    status: "preparation",
    chunkFileList: [],
    uploadedSize: 0
  };
  state.dataSource.push(dataItem);
  const i = state.dataSource.findIndex(item => item.uid == dataItem.uid);
  // 同步计算分片文件和 md5，实时更新计算进度
  // const { md5, chunkFileList } = await createChunkFileAndMd5(
  //   file as RcFile,
  //   chunkCount,
  //   (progress) => {
  //     state.dataSource[i].md5Progress = progress
  //   },
  // )

  // 采用多线程计算和默克尔树计算树根
  const chunks = await cutFile(file);
  const merkleTree = new MerkleTree(chunks.map(chunk => chunk.hash));
  const md5 = merkleTree.getRootHash();
  const chunkFileList = chunks.map(chunk => chunk.blob);
  // console.log(md5, chunkFileList)

  // 更新数据和状态
  state.dataSource[i] = {
    ...state.dataSource[i],
    md5,
    chunkFileList,
    status: "preupload"
  };
  // 清空fileList
  fileList.value = fileList.value.filter(item => item.md5);
};

// 查询文件状态并上传
const onUpload = async () => {
  for (let i = 0; i < state.dataSource.length; i++) {
    // md5 未计算完成和正在上传的跳过（重复点击的情况）
    if (!state.dataSource[i].md5 || state.dataSource[i].status == "uploading") continue;
    await uploadFile(i, state.dataSource[i]);
  }
};

/**
 * 处理fileList
 * @param fileList
 * @returns
 */

const handleFileList = (data: any) => {
  !fileList.value.find(item => item.md5 == data.md5) && fileList.value.push(data);
  fileList.value = fileList.value.filter(item => item.md5);
};

/**
 * 上传处理方法
 * @param index 如果直接修改 item，在上传过程中，item一直在被更改，而循环传入的 item 却一直是初始值，因此需要 index 确定当前 item 的最新值
 * @param item
 */
const uploadFile = async (index: number, item: FileTableDataType) => {
  const { code, data } = await checkFileByMd5(item.md5);
  state.dataSource[index].status = "uploading";
  if (code === HttpCodeUploadEnum.SUCCESS) {
    n++;
    //  上传成功
    state.dataSource[index].progress = 100;
    state.dataSource[index].status = "success";
    handleFileList(data);
    emits("success", data);
    emits("change", fileList.value);
    if (state.dataSource.length === n) closeHandler();
    return;
  } else if (code === HttpCodeUploadEnum.FAIL) {
    //  上传失败
    state.dataSource[index].status = "error";
    return;
  } /*  else if (code === HttpCodeUploadEnum.UPLOADING) {
        // 上传中，返回已上传的文件数据和分片列表
      } else {
        // 未上传
      } */

  // 返回需要上传分片和对应地址
  const needUploadFile = await initSliceFile(item, data);
  console.log("需要上传的文件", needUploadFile);
  const totalSize = needUploadFile.reduce((pre, cur) => pre + cur.file.size, 0);

  // plimit 并发上传
  const uploadLimit = needUploadFile.map(n => limit(() => uploadChunkUrl(n, index, totalSize, item.file.type)));

  const results = await Promise.allSettled(uploadLimit);
  const errResults = results.filter(r => r.status === "rejected");

  if (errResults.length > 0) {
    console.warn(item.name + " 上传失败的分片-----", errResults);
    state.dataSource[index].status = "error";
    return;
  }

  try {
    const { code, data } = await mergeFileByMd5(item.md5);
    if (code === 10000) {
      n++;
      state.dataSource[index].status = "success";
      state.dataSource[index].progress = 100;
      handleFileList(data);
      emits("success", data);
      emits("change", fileList.value);
      if (state.dataSource.length === n) closeHandler();
    }
  } catch (error) {
    console.log(error);
    state.dataSource[index].status = "error";
  }
};

// 初始化分片操作并将分片文件和其上传地址一一对应
const initSliceFile = async (item: FileTableDataType, initData: UploadFileInfoType) => {
  //  只有上传中的分片文件才会有 initData 数据，用 {} 做兜底
  const { uploadId, listParts } = initData || {};

  // 初始化分片参数
  const param: UploadFileInfoType = {
    uploadId,
    originalFileName: item.name,
    size: item.size,
    chunkSize: CHUNK_SIZE,
    chunkCount: item.chunkCount,
    md5: item.md5,
    contentType: item.file.type,
    prefix: props.prefixData,
    userId: userStore.userInfo.id
  };

  const needUploadFile: ChunkFileUrlType[] = [];

  const { code, data } = await initMultPartFile(param);
  if (code !== 10000) return [];

  // 存放需要去上传的文件数据
  if ((listParts || []).length == 0) {
    // 若全都没有上传，一一对应，其中 urls 是所有分片上传的 url 集合
    item.chunkFileList.forEach((item, index) => {
      needUploadFile.push({ url: data.urls[index], file: item });
    });
    return needUploadFile;
  }

  // 存在上传的，对比 minio 已上传的 listParts（序号），将已上传的过滤掉，只上传未上传的文件
  item.chunkFileList.forEach((item, index) => {
    // listParts 索引是从 1 开始的
    const i = (listParts || []).findIndex(v => index + 1 == v);
    if (i === -1) {
      needUploadFile.push({ url: data.urls[index], file: item });
    }
  });

  return needUploadFile;
};

// 根据分片上传地址将分片直传至 minio
const uploadChunkUrl = (chunkItem: ChunkFileUrlType, i: number, totalSize: number, type: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    axios
      .put(chunkItem.url, chunkItem.file, {
        headers: { "Content-Type": type || "application/octet-stream" }
      })
      .then(res => {
        if (res.status !== 200) {
          reject(chunkItem);
        } else {
          // 已上传的文件大小更新，上传进度更新
          const newUploaedSize = state.dataSource[i].uploadedSize + chunkItem.file.size;
          state.dataSource[i] = {
            ...state.dataSource[i],
            uploadedSize: newUploaedSize,
            progress: Math.floor((newUploaedSize / totalSize) * 100)
          };
          resolve();
        }
      })
      .catch(err => {
        console.error(err);
        reject(chunkItem);
      });
  });
};
const handleExceed = () => {
  ElMessage.warning(`超出上传数量`);
};

const handlePaste = (e: any) => {
  const clipboardData = e.clipboardData;
  clipboardDataList.value = [...clipboardData.files];
  if (!clipboardData.files.length) return;
  clipboardDataList.value =
    state.dataSource.length < props.limitNumber
      ? clipboardDataList.value.slice(0, props.limitNumber - state.dataSource.length)
      : [];
  for (const file of clipboardDataList.value) {
    file.uid = generateUUID();
    selectFile({ raw: file, uid: file.uid });
  }
};
</script>
<style lang="scss" scoped>
.el-card-custom {
  width: 100%;
  overflow: hidden;
  position: relative;
  .tip-upload {
    position: absolute;
    font-size: 12px;
    color: red;
    top: 10px;
    opacity: 0.4;
    cursor: pointer;
  }
}
:deep(.avatar-uploader) {
  .el-upload {
    position: relative;
    width: 100%;
    overflow: hidden;
    cursor: pointer;
    border: 1px dashed #8c939d;
    border-radius: 6px;
    transition: var(--el-transition-duration-fast);
  }
  .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  .el-icon.avatar-uploader-icon {
    width: 100%;
    height: 94px;
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }
}
.flx-end {
  display: flex;
  justify-content: flex-end;
}
.upload-list {
  .list-item {
    position: relative;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 94px;
    padding: 15px;
    margin-top: 10px;
    border: 1px solid var(--el-border-color);
    border-radius: 6px;
    .list-left {
      display: flex;
      flex-flow: column nowrap;
      width: 80%;
      .title {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .delete {
      position: absolute;
      top: 10px;
      right: 10px;
      font-size: 14px;
      cursor: pointer;
    }
  }
  .write {
    color: #ffffff;
  }
}
.isNone {
  display: none;
}
</style>
